import requests
import config


class parseCourseData:
    def __init__(self, cookies: dict):
        self.cookies = cookies
        self.courseList = self.getCourseList()
        self.result = []
        self.parseAll()

    def getCourseList(self):
        data = config.data
        response = requests.post('https://byyt.ustb.edu.cn/xszykb/queryxszykbzong',
                                 cookies=self.cookies, data=data)
        return response.json()

    def parseWeek(self, week: str) -> list:
        weeks = []
        for seg in week.split(','):
            if '-' in seg:
                # 处理 `2-16双周` 这样的格式
                if '单' in seg or '双' in seg:
                    Start, End = seg[:-1].split('-')
                    weeks.extend([i for i in range(int(Start), int(End) + 1, 2)])
                else:
                    Start, End = seg.split('-')
                    weeks.extend([i for i in range(int(Start), int(End) + 1)])
            else:
                weeks.append(int(seg))
        return weeks

    def parseTime(self, Time: str) -> int:
        a, b = int(Time[2]), int(Time[-1])  # 表示周a第b节课
        return (a - 1) * 6 + b

    def merge(self, info: dict):
        for course in self.result:
            if course['id'] == info['id']:
                course['courseList'].extend(info['courseList'])
                return
        self.result.append(info)

    def parseAll(self):
        for course in self.courseList:
            # 判断是否有上课时间
            if 'KEY' not in course.keys() or 'KCWZSM' not in course.keys():
                continue

            d = dict()
            course_number = course['RWH']
            courseTime = course['KEY']
            # 处理单独一行只有一个字符 '-'
            lines = [line for line in course['SKSJ'].split('\n') if line.strip() and line.strip() != '-']
            """
            正常情况：工程制图 陈平 1-16周 教学楼409 xq1_jc3
            错误情况：工科物理实验AI 材料全英文 吴平 1-16周 xq2_jc1
            下面代码是处理这个的
            """

            if not ('周' in lines[2] and any(ch.isdigit() for ch in lines[2])):
                lines[0] += lines[1]
                del lines[1]
            courseName, teacherName, courseWeek, address = lines[:4]
            address = ''.join(address.split('【校本部】'))
            # print(course_number)
            # print(courseName, teacherName, courseWeek, address, courseTime)

            addr = '地点未知' if address == '-' else address
            summary = f'{addr} {teacherName} {courseWeek} 周{courseTime[2]}第{courseTime[6]}节'
            # print(summary)

            d['name'] = courseName
            d['teacher'] = [{'JSM': f'{teacherName}'}]
            d['summary'] = summary

            courseWeek = self.parseWeek(courseWeek[:-1])
            courseTime = self.parseTime(courseTime)
            d['courseList'] = [{'time': (week - 1) * 42 + courseTime, 'location': address} for week in courseWeek]
            d['group'] = 'group'
            d['id'] = course_number
            d['course_serial'] = 1
            d['course_number'] = course_number
            d['type'] = ''
            self.merge(d)


class getStuInfo:
    def __init__(self, cookies: dict):
        self.cookies = cookies
        self.stu_id = self.get_stu_id()
        self.course_list = self.get_course_list()

    def get_stu_id(self):
        stu_id = requests.post('https://byyt.ustb.edu.cn/user/basic', cookies=self.cookies).json()['yhdm']
        return stu_id

    def get_course_list(self):
        data = config.data
        response = requests.post('https://byyt.ustb.edu.cn/xszykb/queryxszykbzong',
                                 cookies=self.cookies, data=data)
        return response.json()


"""
format:
{
'name': '软件工程',
'teacher': [{'JSM': '王忠民'}],
'summary': '(周2,第1节,1-8周 信息楼B203) (周4,第1节,2-8周 信息楼B203) ',
# 一周42节课，下标从1开始
'courseList': [
    {'time': 7, 'location': '信息楼B203'},
    {'time': 49, 'location': '信息楼B203'},
    {'time': 91, 'location': '信息楼B203'},
    {'time': 133, 'location': '信息楼B203'},
    {'time': 187, 'location': '信息楼B203'},
    ......
], 
'group': '', 'id': '202420252006892',
'course_serial': 1004,
'course_number': '4050422',
'type': '学科平台'}
"""
